// pages/address/list/index.js

import { reqAddressList, reqDelAddress } from '@/api/address'
import { swipeCellBehaviors } from '@/behaviors/swipeCell'
const app = getApp()
Page({
  behaviors: [swipeCellBehaviors],
  // 页面的初始数据
  data: {
    flag: null,
    addressList: [],
    swipeCellList: []

  },
  onShow() {
    this.getList()
  },
  onLoad(e) {
    this.setData({
      flag: e.flag
    })
  },
  // 获取列表
  async getList() {
    const { data } = await reqAddressList()
    this.setData({
      addressList: data
    })
  },
  // 去编辑页面
  toEdit(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/modules/setting-module/pages/address/add/index?id=${id}`
    })
  },

  // 删除收货地址
  async deleteFn(e) {
    let id = e.currentTarget.dataset.id
    await reqDelAddress(id)
    this.getList()
    wx.toast({ title: '删除成功' })
  },

  // 选择收货地址
  changeAddress(e) {
    if (+this.data.flag !== 1) return
    const id = e.currentTarget.dataset.id
    const address = this.data.addressList.find(item => item.id === id)
    if (address) {
      app.globalData.address = address
      wx.navigateBack()
    }
  }

})
